<template>
	<view class="home">
		<custom-navbar title="添加教育经历" :show-back="true" @back="handleBack" />

		<view class="content" :style="{ paddingTop: navBarHeight + 'px' }">
			<view class="p30">
				<view class="formdata p4030">
					<up-form label-position="left" :model="formData" :rules="rules" ref="formRef">
						<!-- 毕业院校 -->
						<up-form-item label="毕业院校" prop="school" :borderBottom="true" :required="true" labelWidth="180">
							<up-input v-model="formData.school" placeholder="请输入毕业院校" border="none" clearable
								inputAlign="right"></up-input>
						</up-form-item>

						<!-- 开始日期 -->
						<!-- 开始日期 -->
						<up-form-item label="开始日期" prop="startTime" :borderBottom="true" :required="true"
							labelWidth="180" @click="openDatePicker('start')">
							<up-input v-model="formData.startTime" inputAlign="right" disabled disabledColor="#ffffff"
								placeholder="请选择开始日期" border="none"></up-input>
							<template #right>
								<up-icon name="arrow-right"></up-icon>
							</template>
						</up-form-item>

						<!-- 结束日期 -->
						<up-form-item label="结束日期" prop="endTime" :borderBottom="true" :required="true" labelWidth="180"
							@click="openDatePicker('end')">
							<up-input v-model="formData.endTime" inputAlign="right" disabled disabledColor="#ffffff"
								placeholder="请选择结束日期" border="none"></up-input>
							<template #right>
								<up-icon name="arrow-right"></up-icon>
							</template>
						</up-form-item>

						<!-- 学历 -->
						<up-form-item label="学历" prop="education" :borderBottom="true" :required="true" labelWidth="180"
							@click="educationShow = true">
							<up-input v-model="formData.education" placeholder="请选择学历" border="none" disabled
								disabledColor="#ffffff" inputAlign="right"></up-input>
							<template #right>
								<up-icon name="arrow-right"></up-icon>
							</template>
						</up-form-item>

						<!-- 专业 -->
						<up-form-item label="专业" prop="major" :borderBottom="true" :required="true" labelWidth="180">
							<up-input v-model="formData.major" placeholder="请输入专业" border="none" clearable
								inputAlign="right"></up-input>
						</up-form-item>

						<!-- 内容介绍 -->
						<!-- <up-form-item label="内容介绍" prop="description" :borderBottom="true" labelWidth="180"
							style="height: 170rpx;"> -->
						<view class="form-section">
							<view class="section-title">内容介绍</view>
							<up-textarea v-model="formData.description" placeholder="描述这段学习期间的主要内容" :maxlength="500"
								:custom-style="textareaStyle" count></up-textarea>
						</view>
						<!-- </up-form-item> -->
					</up-form>
				</view>

				<up-button type="primary" text="更新我的简历" :loading="submitting" @click="handleSubmit"
					customStyle="border-radius:10rpx;margin-top:40rpx;"></up-button>
			</view>
		</view>

		<!-- 日期选择器 (共用) -->
		<up-datetime-picker v-model="datePickerValue" :show="datePickerShow" mode="date" :minDate="minDate"
			:maxDate="maxDate" @confirm="handleDateConfirm" @cancel="datePickerShow = false">
		</up-datetime-picker>
		<!-- 学历选择 -->
		<up-picker :columns="educationOptions" v-model="educationData" :show='educationShow'
			@confirm="handleEducationConfirm" placeholder="请选择学历">
		</up-picker>
	</view>
</template>

<script setup>
	import CustomNavbar from '@/components/custom-navbar.vue'
	import {
		ref,
		onMounted,
		computed
	} from 'vue';
	import {
		onLoad
	} from '@dcloudio/uni-app'
	import {
		educationackgrounds
	} from '@/api/talents'
	import {
		getClassification
	} from '@/api/login'

	// 系统信息
	const systemInfo = uni.getSystemInfoSync()
	const navBarHeight = computed(() => systemInfo.statusBarHeight + 44)

	// 学历相关
	const education = ref([])
	const educationOptions = ref([])
	const educationShow = ref(false)
	const educationData = ref("")

	// 处理学历数据
	const processEducationData = (data) => {
		return [data.map(item => item.label)]
	}

	// 日期相关
	const minDate = new Date('1970-01-01').getTime();
	const maxDate = new Date().getTime();
	const datePickerValue = ref(new Date().getTime()); // 默认当前时间
	const datePickerShow = ref(false);
	const currentDateField = ref(''); // 当前正在编辑的日期字段

	// 表单相关
	const formRef = ref(null)
	const submitting = ref(false)
	const isEditMode = ref(false) // 新增：标识是否为编辑模式
	const editId = ref('') // 新增：编辑项的ID

	// 表单数据
	const formData = ref({
		school: '',
		startTime: '',
		endTime: '',
		education: '',
		major: '',
		description: ''
	})
	const textareaStyle = {
		height: '200rpx',
		backgroundColor: '#f7f7f7',
		padding: '20rpx',
		borderRadius: '12rpx'
	}
	// 校验规则
	const rules = {
		school: [{
				required: true,
				message: '请输入毕业院校',
				trigger: 'blur'
			},
			{
				min: 2,
				max: 50,
				message: '学校名称长度为2-50个字符',
				trigger: 'blur'
			}
		],
		startTime: [{
			required: true,
			message: '请选择开始日期',
			trigger: 'change'
		}],
		endTime: [{
				required: true,
				message: '请选择结束日期',
				trigger: 'change'
			},
			{
				validator: (rule, value, callback) => {
					if (formData.value.startTime && value && new Date(value) < new Date(formData.value
							.startTime)) {
						callback(new Error('结束日期不能早于开始日期'))
					} else {
						callback()
					}
				},
				trigger: 'change'
			}
		],
		education: [{
			required: true,
			message: '请选择学历',
			trigger: 'change'
		}],
		major: [{
				required: true,
				message: '请输入专业',
				trigger: 'blur'
			},
			{
				min: 2,
				max: 30,
				message: '专业名称长度为2-30个字符',
				trigger: 'blur'
			}
		],
		description: [{
			max: 500,
			message: '内容介绍不能超过500个字符',
			trigger: 'blur'
		}]
	}

	// 方法
	const handleBack = () => {
		uni.navigateBack()
	}

	// 获取学历数据
	const fetchEducationData = async () => {
		try {
			const res = await getClassification(12) // 假设12是学历分类的type
			education.value = res.data
			educationOptions.value = processEducationData(education.value)
		} catch (error) {
			console.error('获取学历数据失败:', error)
			uni.showToast({
				title: '加载学历数据失败',
				icon: 'none'
			})
		}
	}

	// 学历选择确认
	const handleEducationConfirm = (e) => {
		const selectedLabel = e.value[0]
		const selectedItem = education.value.find(item => item.label === selectedLabel)

		if (selectedLabel) {
			formData.value.education = selectedLabel
			educationData.value = selectedLabel
		}

		educationShow.value = false
	}
	// 打开日期选择器
	const openDatePicker = (field) => {
		currentDateField.value = field;

		// 设置默认值
		if (formData.value[`${field}Time`]) {
			// 如果已有值，解析为日期对象
			const match = formData.value[`${field}Time`].match(/(\d+)年(\d+)月/);
			if (match) {
				const year = parseInt(match[1]);
				const month = parseInt(match[2]) - 1; // 月份从0开始
				datePickerValue.value = new Date(year, month).getTime();
			}
		} else {
			// 没有值则使用当前日期
			datePickerValue.value = new Date().getTime();
		}

		datePickerShow.value = true;
	};
	// 日期确认
	const handleDateConfirm = (e) => {
		const date = new Date(e.value);
		const year = date.getFullYear();
		const month = date.getMonth() + 1;

		// 更新对应的日期字段
		formData.value[`${currentDateField.value}Time`] = `${year}年${month}月`;
		datePickerShow.value = false;
	};
	// 提交表单
	// 修改提交方法，区分新增和编辑
	const handleSubmit = async () => {
		try {
			submitting.value = true
			const valid = await formRef.value.validate()
			if (valid) {
				const formatDateForApi = (dateStr) => {
					const match = dateStr.match(/(\d+)年(\d+)月/)
					if (match) {
						const year = match[1]
						const month = match[2].padStart(2, '0')
						return `${year}.${month}`
					}
					return ''
				}

				const submitData = {
					school: formData.value.school,
					startTime: formatDateForApi(formData.value.startTime),
					endTime: formatDateForApi(formData.value.endTime),
					major: formData.value.major,
					education: formData.value.education,
					description: formData.value.description || ''
				}

				// 如果有ID则是编辑，否则是新增
				const params = {
					educationackgrounds: submitData
				}
				if (isEditMode.value && editId.value) {
					params.id = editId.value
				}

				const res = await educationackgrounds(params)

				uni.showToast({
					title: isEditMode.value ? '更新成功' : '添加成功',
					icon: 'success',
					success: () => {
						setTimeout(() => {
							uni.redirectTo({
								url: '/pages/resume/index'
							})
						}, 1500)
					}
				})
			}
		} catch (error) {
			console.error('提交失败:', error)
			uni.showToast({
				title: error.message || '提交失败',
				icon: 'none'
			})
		} finally {
			submitting.value = false
		}
	}

	// 初始化
	onLoad(async (options) => {
		await fetchEducationData()

		// 从本地存储获取编辑数据
		uni.getStorage({
			key: 'currentEducationData',
			success: (res) => {
				if (res.data) {
					isEditMode.value = true
					editId.value = options.id || ''

					// 转换日期格式：从 "2023.07" 转换为 "2023年07月"
					const formatDateForDisplay = (dateStr) => {
						if (!dateStr) return ''
						const [year, month] = dateStr.split('.')
						return `${year}年${month.padStart(2, '0')}月`
					}

					// 填充表单数据
					formData.value = {
						school: res.data.school || '',
						startTime: formatDateForDisplay(res.data.startTime),
						endTime: formatDateForDisplay(res.data.endTime),
						education: res.data.education || '',
						major: res.data.major || '',
						description: res.data.description || ''
					}

					// 设置学历选择器的值
					if (res.data.education) {
						educationData.value = res.data.education
					}

					// 清除本地存储
					uni.removeStorage({
						key: 'currentEducationData'
					})
				}
			},
			fail: (err) => {
				console.log('没有获取到编辑数据，进入新增模式')
			}
		})
	})
</script>

<style lang="scss" scoped>
	.home {
		width: 100%;
		min-height: 100vh;
		background-color: #f7f8fa;

		.content {
			padding-top: var(--status-bar-height);
			padding-top: calc(var(--status-bar-height) + 70rpx);

			.p30 {
				padding: 30rpx;

				.formdata {
					width: 100%;
					background: #FFFFFF;
					border-radius: 20rpx;
					margin-bottom: 40rpx;
					box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);

					.form-section {
						background: #FFFFFF;
						// border-radius: 20rpx;
						// padding: 40rpx 30rpx;
						// box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
						margin-bottom: 40rpx;

						.section-title {
							margin-top: 10rpx;
							margin-bottom: 32rpx;
							font-size: 28rpx;
							color: #333;
							font-weight: 500;
						}
					}

					/* 调整计数器样式 */
					:deep(.u-textarea__count) {
						background: transparent !important;
						color: #999 !important;
					}

					.form-title {
						font-size: 30rpx;
						font-weight: bold;
						color: #333;
						margin-bottom: 45rpx;
					}

					::v-deep .u-form-item {
						height: 90rpx;
					}

					::v-deep .u-form-item__body__right__content {
						justify-content: flex-end;
					}
				}
			}
		}
	}
</style>